﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Application.Dtos;
using Microsoft.Extensions.Logging;
using ERP.ERPModels.EquipmentManage;
using ERP.EquipmentManage.Dtos;
using System.Linq.Dynamic.Core;
using AutoMapper;

namespace ERP.EquipmentManage
{
    /// <summary>
    /// 设备维护计划服务实现
    /// </summary>
    public class EquipmentMaintenancePlanService : ApplicationService, IEquipmentMaintenancePlanService
    {
        private readonly IRepository<EquipmentMaintenancePlan, int> _planRepository;
        private readonly ILogger<EquipmentMaintenancePlanService> _logger;

        public EquipmentMaintenancePlanService(
            IRepository<EquipmentMaintenancePlan, int> planRepository,
            ILogger<EquipmentMaintenancePlanService> logger)
        {
            _planRepository = planRepository;
            _logger = logger;
        }

        /// <summary>
        /// 获取设备维护计划列表
        /// </summary>
        public async Task<PagedResultDto<EquipmentMaintenancePlanDto>> GetListAsync(GetEquipmentMaintenancePlanInputDto input)
        {
            var query = await _planRepository.GetQueryableAsync();

            // 关键字搜索
            if (!string.IsNullOrWhiteSpace(input.Keyword))
            {
                query = query.Where(x => x.PlanCode.Contains(input.Keyword) || x.PlanName.Contains(input.Keyword));
            }

            // 计划编码搜索
            if (!string.IsNullOrWhiteSpace(input.PlanCode))
            {
                query = query.Where(x => x.PlanCode.Contains(input.PlanCode));
            }

            // 计划名称搜索
            if (!string.IsNullOrWhiteSpace(input.PlanName))
            {
                query = query.Where(x => x.PlanName.Contains(input.PlanName));
            }

            // 计划类型搜索
            if (!string.IsNullOrWhiteSpace(input.PlanType))
            {
                query = query.Where(x => x.PlanType.Contains(input.PlanType));
            }

            // 状态搜索
            if (!string.IsNullOrWhiteSpace(input.Status))
            {
                query = query.Where(x => x.Status == input.Status);
            }

            // 排序
            if (!string.IsNullOrWhiteSpace(input.Sorting))
            {
                query = query.OrderBy(input.Sorting);
            }
            else
            {
                query = query.OrderByDescending(x => x.CreatedAt);
            }

            // 分页
            var totalCount = await AsyncExecuter.CountAsync(query);
            var items = await AsyncExecuter.ToListAsync(query.PageBy(input.SkipCount, input.MaxResultCount));

            var dtos = items.Select(entity => {
                var dto = ObjectMapper.Map<EquipmentMaintenancePlan, EquipmentMaintenancePlanDto>(entity);
                dto.StatusText = GetStatusText(entity.Status);
                return dto;
            }).ToList();

            return new PagedResultDto<EquipmentMaintenancePlanDto>(totalCount, dtos);
        }

        /// <summary>
        /// 根据ID获取设备维护计划
        /// </summary>
        public async Task<EquipmentMaintenancePlanDto> GetAsync(int id)
        {
            var entity = await _planRepository.GetAsync(id);
            var dto = ObjectMapper.Map<EquipmentMaintenancePlan, EquipmentMaintenancePlanDto>(entity);
            dto.StatusText = GetStatusText(entity.Status);
            return dto;
        }

        /// <summary>
        /// 创建设备维护计划
        /// </summary>
        public async Task<EquipmentMaintenancePlanDto> CreateAsync(CreateEquipmentMaintenancePlanDto input)
        {
            // 检查计划编码是否已存在
            if (await CheckPlanCodeExistsAsync(input.PlanCode))
            {
                throw new Exception($"计划编码 '{input.PlanCode}' 已存在");
            }

            var entity = ObjectMapper.Map<CreateEquipmentMaintenancePlanDto, EquipmentMaintenancePlan>(input);
            entity.CreatedAt = DateTime.Now;
            entity.UpdatedAt = DateTime.Now;
            
            entity = await _planRepository.InsertAsync(entity, true);
            
            _logger.LogInformation("创建设备维护计划成功，ID: {Id}, 计划编码: {PlanCode}", entity.Id, entity.PlanCode);

            var dto = ObjectMapper.Map<EquipmentMaintenancePlan, EquipmentMaintenancePlanDto>(entity);
            dto.StatusText = GetStatusText(entity.Status);
            return dto;
        }

        /// <summary>
        /// 更新设备维护计划
        /// </summary>
        public async Task<EquipmentMaintenancePlanDto> UpdateAsync(int id, UpdateEquipmentMaintenancePlanDto input)
        {
            var entity = await _planRepository.GetAsync(id);

            // 检查计划编码是否已存在（排除当前记录）
            if (await CheckPlanCodeExistsAsync(input.PlanCode, id))
            {
                throw new Exception($"计划编码 '{input.PlanCode}' 已存在");
            }

            ObjectMapper.Map(input, entity);
            entity.UpdatedAt = DateTime.Now;
            
            entity = await _planRepository.UpdateAsync(entity, true);
            
            _logger.LogInformation("更新设备维护计划成功，ID: {Id}, 计划编码: {PlanCode}", entity.Id, entity.PlanCode);

            var dto = ObjectMapper.Map<EquipmentMaintenancePlan, EquipmentMaintenancePlanDto>(entity);
            dto.StatusText = GetStatusText(entity.Status);
            return dto;
        }

        /// <summary>
        /// 删除设备维护计划
        /// </summary>
        public async Task DeleteAsync(int id)
        {
            await _planRepository.DeleteAsync(id);
            _logger.LogInformation("删除设备维护计划成功，ID: {Id}", id);
        }

        /// <summary>
        /// 批量删除设备维护计划
        /// </summary>
        public async Task BatchDeleteAsync(List<int> ids)
        {
            if (ids == null || !ids.Any())
            {
                throw new Exception("请选择要删除的记录");
            }

            foreach (var id in ids)
            {
                await _planRepository.DeleteAsync(id);
            }

            _logger.LogInformation("批量删除设备维护计划成功，删除数量: {Count}", ids.Count);
        }

        /// <summary>
        /// 检查计划编码是否已存在
        /// </summary>
        public async Task<bool> CheckPlanCodeExistsAsync(string planCode, int? excludeId = null)
        {
            var query = await _planRepository.GetQueryableAsync();
            query = query.Where(x => x.PlanCode == planCode);

            if (excludeId.HasValue)
            {
                query = query.Where(x => x.Id != excludeId.Value);
            }

            return await AsyncExecuter.AnyAsync(query);
        }

        /// <summary>
        /// 获取状态文本
        /// </summary>
        private string GetStatusText(string status)
        {
            return status switch
            {
                "草稿" => "草稿",
                "已确认" => "已确认",
                "审批中" => "审批中",
                "已审批" => "已审批",
                "已完成" => "已完成",
                "已拒绝" => "已拒绝",
                "已生成生产工单" => "已生成生产工单",
                _ => status ?? "未知"
            };
        }
    }
}
